<template>
  <div class="information-manager">
    <!-- 搜索区域 -->
    <div class="search-area">
      <el-form :inline="true" :model="searchForm" class="demo-form-inline">
        <el-form-item label="断面名称">
          <el-input v-model="searchForm.sectionName" placeholder="请输入断面名称" style="width: 200px;" />
        </el-form-item>
        <el-form-item label="断面类型">
          <el-select v-model="searchForm.sectionType" placeholder="请选择断面类型" style="width: 150px;">
            <el-option label="自动" value="自动" />
            <el-option label="手动" value="手动" />
          </el-select>
        </el-form-item>
        <el-form-item label="断面分类">
          <el-select v-model="searchForm.sectionCategory" placeholder="请选择断面分类" style="width: 150px;">
            <el-option label="河流" value="河流" />
            <el-option label="湖泊" value="湖泊" />
            <el-option label="水库" value="水库" />
          </el-select>
        </el-form-item>
        <el-form-item label="控制级别">
          <el-select v-model="searchForm.controlLevel" placeholder="请选择控制级别" style="width: 150px;">
            <el-option label="国控" value="国控" />
            <el-option label="省控" value="省控" />
            <el-option label="市控" value="市控" />
            <el-option label="县控" value="县控" />
          </el-select>
        </el-form-item>
        <el-form-item label="考核类别">
          <el-select v-model="searchForm.assessmentType" placeholder="请选择考核类别" style="width: 150px;">
            <el-option label="国考" value="国考" />
            <el-option label="省考" value="省考" />
            <el-option label="市考" value="市考" />
            <el-option label="县考" value="县考" />
          </el-select>
        </el-form-item>
        <el-form-item>
          <el-button type="primary" @click="handleSearch">查询</el-button>
          <el-button @click="handleReset">重置</el-button>
        </el-form-item>
      </el-form>
    </div>

    <!-- 操作按钮区域 -->
    <div class="action-area">
      <el-button type="primary" @click="handleAdd">新增</el-button>
      <el-button type="primary" @click="handleUpdate" :disabled="selectedRows.length !== 1">修改</el-button>
      <el-button type="danger" @click="handleDelete" :disabled="selectedRows.length === 0">删除</el-button>
      <el-button @click="handleExport">导出</el-button>
      <el-upload
        style="margin: 0 10px;"
        class="upload-demo"
        :action="importUrl"
        :before-upload="beforeImportUpload"
        :on-success="onImportSuccess"
        :on-error="onImportError"
        accept=".xlsx,.xls"
        :show-file-list="false"
      >
        <el-button>导入</el-button>
      </el-upload>
      <el-button @click="handleDownloadTemplate">下载模板</el-button>
    </div>

    <!-- 项目列表 -->
    <div class="table-area">
      <el-table
        v-loading="loading"
        :data="informationList"
        style="width: 100%"
        @selection-change="handleSelectionChange"
      >
        <el-table-column type="selection" width="55" />
        <el-table-column prop="sectionName" label="断面名称" />
        <el-table-column prop="sectionType" label="断面类型" />
        <el-table-column prop="deviceNumber" label="设备编号" />
        <el-table-column prop="sectionCategory" label="断面分类" />
        <el-table-column prop="administrativeDivision" label="行政区划" />
        <el-table-column prop="controlLevel" label="控制级别" />
        <el-table-column prop="assessmentLevel" label="考核级别" />
        <el-table-column label="操作" width="100" fixed="right">
          <template slot-scope="scope">
            <el-button type="text" size="small" @click="handleEdit(scope.row)">修改</el-button>
            <el-button type="text" size="small" @click="handleRemove(scope.row.id)" style="color: #f56c6c;">删除</el-button>
          </template>
        </el-table-column>
      </el-table>
    </div>

    <!-- 分页 -->
    <div class="pagination-area">
      <el-pagination
        @size-change="handleSizeChange"
        @current-change="handleCurrentChange"
        :current-page="pagination.pageNum"
        :page-sizes="[10, 20, 50, 100]"
        :page-size="pagination.pageSize"
        layout="total, sizes, prev, pager, next, jumper"
        :total="pagination.total"
      />
    </div>

    <!-- 新增/修改弹框 -->
    <el-dialog
      :title="isEdit ? '修改断面信息' : '添加断面信息'"
      :visible.sync="dialogVisible"
      width="600px"
    >
      <el-form :model="formData" :rules="rules" ref="formRef" label-width="120px">
        <el-row>
          <el-col :span="24">
            <el-form-item label="断面名称" prop="sectionName">
              <el-input v-model="formData.sectionName" placeholder="请输入断面名称" />
            </el-form-item>
          </el-col>
        </el-row>
        
        <el-row>
          <el-col :span="12">
            <el-form-item label="断面类型" prop="sectionType">
              <el-select v-model="formData.sectionType" placeholder="请选择断面类型">
                <el-option label="自动" value="自动" />
                <el-option label="手动" value="手动" />
              </el-select>
            </el-form-item>
          </el-col>
          <el-col :span="12">
            <el-form-item label="设备编号" prop="deviceNumber">
              <el-input v-model="formData.deviceNumber" placeholder="请输入设备编号" />
            </el-form-item>
          </el-col>
        </el-row>

        <el-row>
          <el-col :span="12">
            <el-form-item label="断面分类" prop="sectionCategory">
              <el-select v-model="formData.sectionCategory" placeholder="请选择断面分类">
                <el-option label="河流" value="河流" />
                <el-option label="湖泊" value="湖泊" />
                <el-option label="水库" value="水库" />
              </el-select>
            </el-form-item>
          </el-col>
          <el-col :span="12">
            <el-form-item label="行政区划" prop="administrativeDivision">
              <el-select v-model="formData.administrativeDivision" placeholder="请选择行政区划">
                <el-option label="埇桥区" value="埇桥区" />
                <el-option label="其他区" value="其他区" />
              </el-select>
            </el-form-item>
          </el-col>
        </el-row>

        <el-row>
          <el-col :span="12">
            <el-form-item label="控制级别" prop="controlLevel">
              <el-select v-model="formData.controlLevel" placeholder="请选择控制级别">
                <el-option label="国控" value="国控" />
                <el-option label="省控" value="省控" />
                <el-option label="市控" value="市控" />
                <el-option label="县控" value="县控" />
              </el-select>
            </el-form-item>
          </el-col>
          <el-col :span="12">
            <el-form-item label="考核级别" prop="assessmentLevel">
              <el-select v-model="formData.assessmentLevel" placeholder="请选择考核级别">
                <el-option label="国考" value="国考" />
                <el-option label="省考" value="省考" />
                <el-option label="市考" value="市考" />
                <el-option label="县考" value="县考" />
              </el-select>
            </el-form-item>
          </el-col>
        </el-row>

        <el-row>
          <el-col :span="24">
            <el-form-item label="备注">
              <el-input v-model="formData.remark" placeholder="请输入备注" type="textarea" :rows="3" />
            </el-form-item>
          </el-col>
        </el-row>
      </el-form>
      <div slot="footer" class="dialog-footer">
        <el-button @click="dialogVisible = false">取消</el-button>
        <el-button type="primary" @click="handleSubmit">确定</el-button>
      </div>
    </el-dialog>
  </div>
</template>

<script>
import { getInformationList, getInformationDetail, addInformation, updateInformation, deleteInformation, exportInformation, downloadTemplate } from './api/informationApi'
import { parseTime } from '@/utils/ruoyi'

export default {
  name: 'InformationManager',
  data() {
    return {
      searchForm: {
        sectionName: '',
        sectionType: '',
        sectionCategory: '',
        controlLevel: '',
        assessmentType: ''
      },
      informationList: [],
      loading: false,
      selectedRows: [],
      pagination: {
        pageNum: 1,
        pageSize: 10,
        total: 0
      },
      dialogVisible: false,
      isEdit: false,
      formData: {
        id: '',
        sectionName: '',
        sectionType: '',
        deviceNumber: '',
        sectionCategory: '',
        administrativeDivision: '',
        controlLevel: '',
        assessmentLevel: '',
        remark: ''
      },
      rules: {
        sectionName: [
          { required: true, message: '请输入断面名称', trigger: 'blur' }
        ],
        sectionType: [
          { required: true, message: '请选择断面类型', trigger: 'change' }
        ],
        sectionCategory: [
          { required: true, message: '请选择断面分类', trigger: 'change' }
        ],
        controlLevel: [
          { required: true, message: '请选择控制级别', trigger: 'change' }
        ],
        assessmentLevel: [
          { required: true, message: '请选择考核级别', trigger: 'change' }
        ],
        administrativeDivision: [
          { required: true, message: '请选择行政区划', trigger: 'change' }
        ]
      },
      importUrl: '/drinkingwater/information/import'
    }
  },
  created() {
    this.getInformationData()
  },
  methods: {
    // 获取断面信息列表数据
    async getInformationData() {
      this.loading = true
      try {
        const params = {
          ...this.searchForm,
          pageNum: this.pagination.pageNum,
          pageSize: this.pagination.pageSize
        }
        const res = await getInformationList(params)
        if (res.code === 200) {
          this.informationList = res.rows
          this.pagination.total = res.total
        }
      } catch (error) {
        console.error('获取断面信息列表失败:', error)
        this.$message.error('获取断面信息列表失败')
      } finally {
        this.loading = false
      }
    },

    // 处理搜索
    handleSearch() {
      this.pagination.pageNum = 1
      this.getInformationData()
    },

    // 处理重置
    handleReset() {
      this.searchForm = {
        sectionName: '',
        sectionType: '',
        sectionCategory: '',
        controlLevel: '',
        assessmentType: ''
      }
      this.getInformationData()
    },

    // 处理新增
    handleAdd() {
      this.isEdit = false
      this.resetForm()
      this.dialogVisible = true
    },

    // 处理修改
    async handleEdit(row) {
      this.isEdit = true
      this.resetForm()
      try {
        const res = await getInformationDetail(row.id)
        if (res.code === 200) {
          this.formData = { ...res.data }
        }
      } catch (error) {
        console.error('获取断面信息详情失败:', error)
        this.$message.error('获取断面信息详情失败')
      }
      this.dialogVisible = true
    },

    // 处理批量修改
    handleUpdate() {
      if (this.selectedRows.length === 1) {
        this.handleEdit(this.selectedRows[0])
      }
    },

    // 处理删除
    handleRemove(id) {
      this.$confirm('确定要删除该断面信息吗？', '提示', {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'warning'
      }).then(async () => {
        try {
          const res = await deleteInformation(id)
          if (res.code === 200) {
            this.$message.success('删除成功')
            this.getInformationData()
          } else {
            this.$message.error(res.msg || '删除失败')
          }
        } catch (error) {
          console.error('删除断面信息失败:', error)
          this.$message.error('删除断面信息失败')
        }
      })
    },

    // 处理批量删除
    handleDelete() {
      this.$confirm(`确定要删除选中的 ${this.selectedRows.length} 条断面信息吗？`, '提示', {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'warning'
      }).then(async () => {
        try {
          const ids = this.selectedRows.map(row => row.id).join(',')
          const res = await deleteInformation(ids)
          if (res.code === 200) {
            this.$message.success('删除成功')
            this.getInformationData()
            this.selectedRows = []
          } else {
            this.$message.error(res.msg || '删除失败')
          }
        } catch (error) {
          console.error('删除断面信息失败:', error)
          this.$message.error('删除断面信息失败')
        }
      })
    },

    // 处理导出
    async handleExport() {
      try {
        const res = await exportInformation(this.searchForm)
        const blob = new Blob([res], { type: 'application/vnd.ms-excel' })
        const url = window.URL.createObjectURL(blob)
        const link = document.createElement('a')
        link.href = url
        link.download = `断面信息_${parseTime(new Date(), '{yyyy}{mm}{dd}')}.xlsx`
        link.click()
        window.URL.revokeObjectURL(url)
      } catch (error) {
        console.error('导出断面信息失败:', error)
        this.$message.error('导出断面信息失败')
      }
    },

    // 下载模板
    async handleDownloadTemplate() {
      try {
        const res = await downloadTemplate()
        const blob = new Blob([res], { type: 'application/vnd.ms-excel' })
        const url = window.URL.createObjectURL(blob)
        const link = document.createElement('a')
        link.href = url
        link.download = `断面信息导入模板.xlsx`
        link.click()
        window.URL.revokeObjectURL(url)
      } catch (error) {
        console.error('下载模板失败:', error)
        this.$message.error('下载模板失败')
      }
    },

    // 提交表单
    async handleSubmit() {
      this.$refs.formRef.validate(async (valid) => {
        if (valid) {
          try {
            let res
            if (this.isEdit) {
              res = await updateInformation(this.formData)
            } else {
              res = await addInformation(this.formData)
            }
            if (res.code === 200) {
              this.$message.success(this.isEdit ? '修改成功' : '新增成功')
              this.dialogVisible = false
              this.getInformationData()
            } else {
              this.$message.error(res.msg || (this.isEdit ? '修改失败' : '新增失败'))
            }
          } catch (error) {
            console.error(`${this.isEdit ? '修改' : '新增'}断面信息失败:`, error)
            this.$message.error(`${this.isEdit ? '修改' : '新增'}断面信息失败`)
          }
        }
      })
    },

    // 重置表单
    resetForm() {
      this.formData = {
        id: '',
        sectionName: '',
        sectionType: '',
        deviceNumber: '',
        sectionCategory: '',
        administrativeDivision: '',
        controlLevel: '',
        assessmentLevel: '',
        remark: ''
      }
      if (this.$refs.formRef) {
        this.$refs.formRef.resetFields()
      }
    },

    // 处理表格选择变化
    handleSelectionChange(rows) {
      this.selectedRows = rows
    },

    // 处理分页大小变化
    handleSizeChange(size) {
      this.pagination.pageSize = size
      this.getInformationData()
    },

    // 处理当前页码变化
    handleCurrentChange(current) {
      this.pagination.pageNum = current
      this.getInformationData()
    },

    // 导入文件前的校验
    beforeImportUpload(file) {
      const isExcel = file.name.endsWith('.xlsx') || file.name.endsWith('.xls')
      if (!isExcel) {
        this.$message.error('只能上传Excel文件！')
        return false
      }
      return true
    },

    // 导入文件成功处理
    onImportSuccess(response) {
      if (response.code === 200) {
        this.$message.success(response.msg || '导入成功')
        this.getInformationData()
      } else {
        this.$message.error(response.msg || '导入失败')
      }
    },

    // 导入文件失败处理
    onImportError(error) {
      this.$message.error('导入失败')
    }
  }
}
</script>

<style scoped>
.information-manager {
  padding: 20px;
}

.search-area {
  /* margin-bottom: 20px; */
}

.action-area {
  /* margin-bottom: 20px; */
  display: flex;
  align-items: center;
}

.action-area .el-button {
  /* margin-right: 10px; */
}

.table-area {
  margin-bottom: 20px;
}

.pagination-area {
  text-align: right;
}
</style>